package com.ruoyi.common.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.ruoyi.common.core.domain.R;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局异常
 *
 * @author ruoyi
 */
public class GlobalException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 错误提示
     */
    private String message;

    /**
     * 错误明细，内部调试错误
     * <p>
     * 和 {@link CommonResult#getDetailMessage()} 一致的设计
     */
    private String detailMessage;

    /**
     * 空构造方法，避免反序列化问题
     */
    public GlobalException() {
    }

    public GlobalException(String message) {
        this.message = message;
    }

    public String getDetailMessage() {
        return detailMessage;
    }

    public GlobalException setDetailMessage(String detailMessage) {
        this.detailMessage = detailMessage;
        return this;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public GlobalException setMessage(String message) {
        this.message = message;
        return this;
    }
    //处理token异常
    @ExceptionHandler(SaTokenException.class)
    public R<Void> handlerSaTokenException(SaTokenException e) {

        // 根据不同异常细分状态码返回不同的提示
        if(e.getCode() == 11001 || e.getCode() == 11011) {
            return R.fail("未能读取到有效Token");
        }
        if(e.getCode() == 11012) {
            return R.fail("Token无效");
        }
        if(e.getCode() == 11013) {
            return R.fail("登录已过期");
        }
        if(e.getCode() == 11014) {
            return R.fail("已被顶下线");
        }
        if(e.getCode() == 11015) {
            return R.fail("已被踢下线");
        }
        if(e.getCode() == 11016) {
            return R.fail("Token已临时过期");
        }
        // 更多 code 码判断 ...

        // 默认的提示
        return R.fail("token 处理异常: " + e.getMessage());
    }
}
